import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UsersEntity } from './users.entity';
export interface PostsRo {
  list: UsersEntity[];
  count: number;
}
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UsersEntity)
    private readonly usersRepository: Repository<UsersEntity>,
  ) {}

  // 创建用户
  async create(user: Partial<UsersEntity>): Promise<UsersEntity> {
    const { username } = user;
    if (!username) {
      throw new HttpException('缺少用户名称', 401);
    }

    return await this.usersRepository.save(user);
  }

  // 获取所有用户
  async findAll(): Promise<any[]> {
    return this.usersRepository.find();
  }

  // 更新用户
  async updateById(id, user): Promise<UsersEntity> {
    const existUser = await this.usersRepository.findOne({ where: { id } });
    if (!existUser) {
      throw new HttpException(`id为${id}的用户不存在`, 401);
    }
    const updatePost = this.usersRepository.merge(existUser, user);
    return this.usersRepository.save(updatePost);
  }

  // 获取指定用户
  async findById(id): Promise<UsersEntity> {
    return this.usersRepository.findOne({ where: { id } });
  }

  // 删除用户
  async remove(id) {
    const existUser = await this.usersRepository.findOne({ where: { id } });
    if (!existUser) {
      throw new HttpException(`id为${id}的用户不存在`, 401);
    }
    return await this.usersRepository.remove(existUser);
  }
}
